package com.k2data.k2app.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.k2data.k2app.common.ResponseConstant;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.utils.StringUtils;
import lombok.extern.log4j.Log4j2;

import java.util.*;

/**
 *
 * Created by clb on 17-4-5.
 */
@Log4j2
public class JsonUtils {
	/**
	 * 将json转化成map
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, Object> convertJsonStrToMap(Object jsonStr)  throws K2ResponseException{
		if(jsonStr == null){
			return new HashMap<>();
		}
		if(StringUtils.isEmpty(jsonStr.toString())){
			return new HashMap<>();
		}
		try{
			Map<String, Object> map = JSON.parseObject(
					jsonStr.toString(),new TypeReference<Map<String, Object>>(){} );
			return map;
		}catch (Exception e){
			throw new K2ResponseException(ResponseConstant.ID_NOT_FOUND,
					String.format("%s","json转换为map出错"));
		}
	}

	/**
	 * 将json转化成list
	 * @param jsonStr
	 * @return
	 */
	public static List convertJsonStrToList(Object jsonStr){
		Optional<Object> optional = Optional.ofNullable(jsonStr);
		List list = new ArrayList();
		if(optional.isPresent()){
			if(!StringUtils.isEmpty(jsonStr.toString())&&jsonStr.toString().startsWith("[")&&jsonStr.toString().endsWith("]")){
				list = JSON.parseArray(jsonStr.toString());
			}
		}
		return list;
	}
	/**
	 * 将json转化为实体POJO
	 * @param jsonStr
	 * @param obj
	 * @return
	 */
	public static<T> Object JSONToObj(String jsonStr,Class<T> obj) throws K2ResponseException {
		T t = null;
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			//值可以不要双引号
			objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
			objectMapper.configure(JsonParser.Feature.ALLOW_MISSING_VALUES, true);
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//实体对象中不包含则不赋值，不报错
			t = objectMapper.readValue(jsonStr,obj);
		} catch (Exception e) {
			e.printStackTrace();
			throw new K2ResponseException(ResponseConstant.GENERAL,
					String.format("%s","json转换为对象出错"));
		}
		return t;
	}

	/**
	 * 将json转化为实体POJO
	 * @param map
	 * @return
	 */
	public static Object mapToJson(Object map) throws K2ResponseException {
		return JSON.toJSON(map);
	}
}
